package cn.gem.rainbow.cfg.web.interceptor;

import cn.gem.rainbow.cfg.SystemParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 首先，拦截器不属于 JavaWeb三要素Filter, Servlet,Listener
 *  一般说的拦截器都是指SpringMvc里的拦截器，
 *  拦截器的特点是
 *  1.只对 Request做拦截处理
 *  2.拦截器是在 过滤器 (过滤完 request请求 )后，才执行
 *
 *  使用场景:
 *  1.登录权限拦截，判断request是否有权限访问系统
 *  2.拦截特定请求参数
 *
 *
 * 多个拦截器的执行顺序
 * preHandle1-->preHandle2-->
 *              postHandle2--->postHandle1--->
 *              afterCompletion2---->afterCompletion1
 */
@Configuration
public class WebInterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private SystemParam systemParam;

    @Bean
    public HandlerInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

    @Bean
    public HandlerInterceptor customInterceptor() {
        return new CustomInterceptor();
    }

    /**
     * Add Spring MVC lifecycle interceptors for pre- and post-processing of
     * controller method invocations and resource handler requests.
     * Interceptors can be registered to apply to all requests or be limited
     * to a subset of URL patterns.
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //excludePathPatterns 配置不拦截
        //addPathPatterns 拦截
        //order 执行顺序
        registry.addInterceptor(jwtInterceptor())
                // jwt 白名单
                .excludePathPatterns(systemParam.getWhitelist())
                .order(1);

        registry.addInterceptor(customInterceptor())
                .excludePathPatterns(systemParam.getWhitelist())
                .order(2);

//        ir.addPathPatterns(pathConfig.getInclude()); // 拦截
//        ir.excludePathPatterns(pathConfig.getExclude());// 配置不拦截

    }
}
